# -*- coding: iso-8859-15 -*-

#    SuperClipboard is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gtk
from NetworkClient import NetworkClient
from copy import deepcopy

class WindowNetworkClientsSettings(gtk.Window):
    
    def __init__(self,copier=None):
        gtk.Window.__init__(self,type=gtk.WINDOW_TOPLEVEL)
        self.copier = copier
        self.copier.gui.windows.append(self)
        self.set_title("Network Clients Settings")
        self.set_icon_from_file(self.copier.config.path['Ico'])
        self.set_resizable(False)
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.connect("delete-event",self.delete_event_callback)
        self.tmpclient = deepcopy(self.copier.config.getNetworkClients())
        self.build_window()
        
    def build_window(self): 
        main_vbox = gtk.VBox(False, 15)
        self.add(main_vbox)
        submain_hbox = gtk.HBox(False,5)
        client_vbox = gtk.VBox(False,15)
        submain_hbox.pack_start(client_vbox)
        main_vbox.pack_start(submain_hbox)
        
        
        self.liststore = gtk.ListStore(str)
        treeview = gtk.TreeView(self.liststore)
        self.selection = treeview.get_selection()
        self.selection.connect("changed",self.change_selection)
        
        scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled_window.add_with_viewport(treeview)
        scrolled_window.set_size_request(130,180)
        
        column = gtk.TreeViewColumn('Nom du client')
        treeview.append_column(column)
        self.cell = gtk.CellRendererText()
        column.pack_start(self.cell,True)
        column.add_attribute(self.cell, "text" ,0)
        client_vbox.pack_start(scrolled_window)
        
        self.info_vbox = gtk.VBox(False,0)
        submain_hbox.pack_start(self.info_vbox)
 
        button_hbox = gtk.HBox(True)
        client_vbox.pack_start(button_hbox)
        
        addclientbutton = gtk.Button("add")
        addclientbutton.connect("clicked",self.addclient_callback)
        button_hbox.pack_start(addclientbutton)
        
        rmclientbutton = gtk.Button("del")
        rmclientbutton.connect("clicked",self.delclient_callback)
        button_hbox.pack_start(rmclientbutton)
 
        
        self.name_label = gtk.Label()
        name_hbox = gtk.HBox(True)
        name_hbox.pack_start(gtk.Label("Nom"))
        name_hbox.pack_start(self.name_label)

        self.ip_entry = gtk.Entry()
        self.ip_entry.connect("changed",self.changeEntry)
        ip_hbox = gtk.HBox(True)
        ip_hbox.pack_start(gtk.Label("Ip/Hostname"))
        ip_hbox.pack_start(self.ip_entry)
        
        
        self.port_spinner = gtk.SpinButton(gtk.Adjustment(1, 1, 65635, 1.0, 1.0, 0.0))
        self.port_spinner.set_wrap(True)
        self.port_spinner.connect("changed",self.changeEntry)
        port_hbox = gtk.HBox(True)
        port_hbox.pack_start(gtk.Label("Port"))
        port_hbox.pack_start(self.port_spinner)
        
        self.password_entry = gtk.Entry()
        self.password_entry.connect("changed",self.changeEntry)
        password_hbox = gtk.HBox(True)
        password_hbox.pack_start(gtk.Label("Password"))
        password_hbox.pack_start(self.password_entry)
        
        self.number_spinner = gtk.SpinButton(gtk.Adjustment(1, 1, 20, 1.0, 1.0, 0.0))
        self.number_spinner.set_wrap(True)
        self.number_spinner.connect("changed",self.changeEntry)
        number_hbox = gtk.HBox(False, 5)
        number_hbox.pack_start(gtk.Label("Number of elements"))
        number_hbox.pack_start(self.number_spinner)
        
        
        check_server_hbox = gtk.HBox(False,5)
        self.checkserver = gtk.CheckButton()
        check_server_hbox.pack_start(gtk.Label('Connected'))
        check_server_hbox.pack_start(self.checkserver)
        
        self.checkserver.connect("toggled",self.changeEntry)

        self.checkbutton = gtk.Button("Test")
        self.checkbutton.connect("clicked",self.checkbutton_callback)
        hbox = gtk.HBox(False)
        hbox.pack_start(self.checkbutton)
       
        
        
        self.info_vbox.pack_start(name_hbox)
        self.info_vbox.pack_start(ip_hbox)
        self.info_vbox.pack_start(port_hbox)
        self.info_vbox.pack_start(password_hbox)
        self.info_vbox.pack_start(number_hbox)
        self.info_vbox.pack_start(check_server_hbox)
        self.info_vbox.pack_start(hbox)
        
        
        validate_hbox= gtk.HBox(True,5)
        main_vbox.pack_start(validate_hbox)
        
        validate_validate_button = gtk.Button('OK')
        validate_validate_button.connect('clicked',self.validate_callback)
        
        validate_cancel_button = gtk.Button('Cancel')
        validate_cancel_button.connect('clicked',self.destroy_callback)
        
        validate_hbox.pack_start(validate_cancel_button)
        validate_hbox.pack_start(validate_validate_button)
        
        self.show_all()
        self.refresh_store()
        self.selectFirstRow()
       

#Function
    def refresh_store(self):
        if len(self.tmpclient) < 1:
            self.info_vbox.hide_all()
        else:
            self.info_vbox.show_all()
        
        self.liststore.clear()
        for client in self.tmpclient:
            self.liststore.append([client['name']])
            
    def getSelectedClient(self):
        try:
            iter = self.selection.get_selected()[1]
            selectedname = self.liststore.get_value(iter, 0)
            return self.getClientByName(selectedname)
        except:
            return None
        
        
    def getClientByName(self,name):
        for client in self.tmpclient:
            if client['name'] == name:
                return client
        return None
    
    def selectFirstRow(self):
        if ((len(self.tmpclient) >= 1) and (self.liststore.get_iter_first() != None)):
            self.selection.select_iter(self.liststore.get_iter_first())
#Callback      
    def addclient_callback(self,element=None):
        boite = gtk.Dialog("Enter the name of client", self,
            gtk.DIALOG_MODAL,
            (gtk.STOCK_OK, gtk.RESPONSE_OK))
        entry = gtk.Entry()
        boite.vbox.pack_start(gtk.Label('Enter the name of client'))
        boite.vbox.pack_start(entry)
        boite.vbox.show_all()
        reponse = boite.run()
        if ((reponse == gtk.RESPONSE_OK) and (entry.get_text() != "")):
            exist = False
            for client in self.tmpclient:
                if client['name'] == entry.get_text():
                    self.copier.gui.error('Name already exist')
                    exist = True
                    
            if exist == False:
                self.tmpclient.append({
                                       'name' : entry.get_text(),
                                       'ip' : "",
                                       'port' : 34067,
                                       'password' : "",
                                       'number' : 10,
                                       'enable' : False,
                                       })
                self.refresh_store()
                self.selection.select_iter(self.liststore.get_iter((len(self.tmpclient)-1,)))   
        boite.destroy()

        
    def delclient_callback(self,element=None):
        self.tmpclient.remove(self.getSelectedClient())
        self.refresh_store()
        self.selectFirstRow()
    
    def checkbutton_callback(self,element=None):
        try:
            check = NetworkClient.CheckClient(self.ip_entry.get_text(), int(self.port_spinner.get_text()),self.password_entry.get_text()) 
        except Exception as e:
            print e
            check = False
        if check:
            str = "Connection Ok"
        else:
            str = "Connection Failed"
        boite = gtk.Dialog("Check Client", self,
                gtk.DIALOG_MODAL,
                (gtk.STOCK_OK, gtk.RESPONSE_OK))
        boite.vbox.pack_start(gtk.Label(str))
        boite.vbox.show_all()
        boite.run()
        boite.destroy()
        
    def change_selection(self,selection):
        tmpclient = self.getSelectedClient()
        if tmpclient != None:
            self.name_label.set_text(tmpclient['name'])
            self.ip_entry.set_text(tmpclient['ip'])
            self.port_spinner.set_value(int(tmpclient['port']))
            self.number_spinner.set_value(int(tmpclient['number']))
            self.password_entry.set_text(tmpclient['password'])
            self.checkserver.set_active(tmpclient['enable'])
            self.info_vbox.show_all()
        else:
            self.info_vbox.hide_all()
            
    def changeEntry(self,element):
        tmp = self.getClientByName(self.name_label.get_text())
        if tmp != None:
            if element == self.ip_entry:
                tmp['ip'] = self.ip_entry.get_text()
            elif element == self.port_spinner:
                try:
                    tmp['port'] = int(self.port_spinner.get_text())
                except:
                    pass
            elif element == self.checkserver:
                tmp['enable'] = self.checkserver.get_active()
            elif element == self.number_spinner:
                try:
                    tmp['number'] = int(self.number_spinner.get_text())
                except:
                    pass
            elif element ==self.password_entry:
                tmp['password'] = self.password_entry.get_text()
                
    def validate_callback(self,element=None):
        for client in self.tmpclient:
            exist = False
            for runningclient in self.copier.runningclient:
                if client['name'] == runningclient.cliconfig['name']:
                    exist = True
                    if client['number']!= runningclient.cliconfig['number']:
                        if client['number'] < runningclient.cliconfig['number']:
                            i = runningclient.cliconfig['number']
                            while i > client['number']:
                                runningclient.rmElement(i)
                                i-=1
                        runningclient.cliconfig['number']=client['number']
                    if client != runningclient.cliconfig:
                        if client['enable']:
                            thcli = NetworkClient(self.copier, client)
                            self.copier.runningclient.append(thcli)
                            thcli.start()
                        else:
                            runningclient.stopConnection()
                            self.copier.runningclient.remove(runningclient)
            if ((not exist) and (client['enable'] == True)):
                thcli = NetworkClient(self, client)
                self.copier.runningclient.append(thcli)
                thcli.start()
        
        self.copier.config.network['Client'] = self.tmpclient        
        self.copier.savenetworksettings()    
        self.destroy_callback()
    
    def delete_event_callback(self,*args):
        self.destroy_callback()
    
    def destroy_callback(self,element=None):
        self.copier.gui.windows.remove(self)
        self.destroy()